package main

import (
	"admin/contrib/conn"
	"admin/contrib/session"
	"admin/middleware"
	"admin/model"
	"admin/pkg"
	"admin/router"
	"common/config"
	myconn "common/conn"
	"common/helper"
	myredis "common/redis"
	"common/userHelp"
	"context"
	"fmt"
	"github.com/BurntSushi/toml"
	"github.com/meilisearch/meilisearch-go"
	"github.com/robfig/cron/v3"
	"github.com/valyala/fasthttp"
	_ "go.uber.org/automaxprocs"
	"log"
	"os"
	"path/filepath"
)

func main() {

	//argc := len(os.Args)
	//if argc != 3 {
	//	fmt.Printf("%s <c\r\n", os.Args[0])
	//	return
	//}
	passphrase := "myverystrongpasswordo32bitlength" // 32字节的密钥
	configFile := "br1.enc"                          // 加密后的配置文件路径

	// 读取并解密配置文件
	decryptedData, err := helper.LoadEncryptedConfig(configFile, passphrase)
	if err != nil {
		log.Fatalf("Error reading encrypted config file: %v", err)
	}
	cfg := pkg.Conf{}
	//endpoints := strings.Split(os.Args[1], ",")
	//apollo.New(endpoints, pkg.ETCDName, pkg.ETCDPass)
	//err := apollo.ParseTomlStruct(os.Args[2], &cfg)
	//if _, err := toml.DecodeFile(os.Args[1], &cfg); err != nil {
	//	fmt.Printf("ParseTomlStruct error: %s", err.Error())
	//	return
	//}
	//apollo.Close()
	//if err != nil {
	//	fmt.Printf("ParseTomlStruct error: %s", err.Error())
	//	return
	//}

	if err := toml.Unmarshal(decryptedData, &cfg); err != nil {
		log.Fatalf("Error parsing config file: %v", err)
	}

	mt := new(model.MetaTable)

	mt.RPCPath = cfg.RPC
	mt.IsDev = cfg.Dev
	mt.MerchantS3 = cfg.Aws

	//mt.IpDB = conn.InitIpDB(cfg.Ipdb)
	mt.Meili = meilisearch.NewClient(meilisearch.ClientConfig{
		Host:   cfg.Meilisearch.Host,
		APIKey: cfg.Meilisearch.Key,
	})
	//Beanstalkd只能在linux环境下部署，目前部署在容器中
	//mt.MerchantBean = conn.BeanNew(cfg.Beanstalkd)

	mt.MasterDB = conn.InitDB(cfg.Db.Admin, cfg.Db.MaxIdleConn, cfg.Db.MaxOpenConn)
	mt.SlaveDB = conn.InitDB(cfg.SlaveDb.Admin, cfg.SlaveDb.MaxIdleConn, cfg.SlaveDb.MaxOpenConn)
	mt.MerchantRedis = conn.InitRedis(cfg.Redis.Addr[0], cfg.Redis.Password, cfg.Redis.Db)
	mt.RedisDBIndex = cfg.Redis.Db
	helper.InitLog()
	config.InitCfg(mt.MasterDB, mt.MerchantRedis)
	myredis.Init(context.Background(), mt.MerchantRedis, mt.MasterDB, mt.SlaveDB, userHelp.LoadUserToRedis)
	userHelp.LoadModuleInit(mt.MasterDB, myredis.SetUserFieldNotLab)

	//本地暂不使用哨兵模式
	//mt.MerchantRedis = conn.InitRedisSentinel(cfg.Redis.Addr, cfg.Redis.Password, cfg.Redis.Sentinel, 0)
	mt.TgPay.AppKey = cfg.Tgpay.AppKey
	session.New(mt.MerchantRedis, cfg.Prefix)
	model.New("0.0.0.0")
	myconn.New("0.0.0.0")
	model.Constructor(mt, cfg.RPC)

	defer func() {
		model.Close()
		mt = nil
	}()

	if os.Args[1] == "game" {
		model.GameFlushAll()
		return
	} else if os.Args[1] == "tag" {
		model.TagFlushAll()
		return
	} else if os.Args[1] == "sms" {
		model.SmsFlushAll()
		return
	} else if os.Args[1] == "member" {
		model.MemberFlushAll()
		return
	} else if os.Args[1] == "message" {
		model.MessageFlushAll()
		return
	}

	mt.Program = filepath.Base(os.Args[0])
	b := router.BuildInfo{
		GitReversion:   pkg.GitReversion,
		BuildTime:      pkg.BuildTime,
		BuildGoVersion: pkg.BuildGoVersion,
	}
	mt.WebUrl = cfg.WebURL
	mt.BannerUrl = cfg.BannerURL
	mt.Callback = cfg.Callback
	app := router.SetupRouter(b)

	c := cron.New(cron.WithSeconds())
	// 在每天凌晨0点执行
	//_, err := c.AddFunc("0 0 0 * * *", model.GiveSpinChance)
	//if err != nil {
	//	log.Fatalln("无法设置定时任务: ", err)
	//}

	// 日况统计 统计数据每五分钟一次 ，服务端统计
	_, err = c.AddFunc("@every 5m", model.CronDailyData)
	if err != nil {
		log.Fatalln("无法设置定时任务: ", err)
	}
	//自动出款
	//_, err = c.AddFunc("@every 5s", model.WithdrawAuto)
	//if err != nil {
	//	log.Fatalln("无法设置定时任务: ", err)
	//}
	c.Start()

	srv := &fasthttp.Server{
		Handler:            middleware.Use(app.Handler),
		ReadTimeout:        router.ApiTimeout,
		WriteTimeout:       router.ApiTimeout,
		Name:               "admin",
		MaxRequestBodySize: 51 * 1024 * 1024,
	}
	fmt.Printf("gitReversion = %s\r\nbuildGoVersion = %s\r\nbuildTime = %s\r\n", pkg.GitReversion, pkg.BuildGoVersion, pkg.BuildTime)
	fmt.Println("admin running", cfg.Port.Admin)

	if err := srv.ListenAndServe(cfg.Port.Admin); err != nil {
		log.Fatalf("Error in ListenAndServe: %s", err)
	}
}
